//
//  RegisterViewController.m
//  iCinema
//
//  Created by Robin Daniels on 21/11/12.
//  Copyright (c) 2012 Robin Daniels. All rights reserved.
//

#import "RegisterViewController.h"
#import "JSONKit.h"
#import "Gebruiker.h"
#import "VariableStore.h"

@interface RegisterViewController ()

@end

@implementation RegisterViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"bg.jpg"]];
    self.view.backgroundColor = background;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    [self setTxtName:nil];
    [self setTxtSurname:nil];
    [self setTxtEmail:nil];
    [self setTxtPass:nil];
    [self setTxtBirth:nil];
    [self setScrollView:nil];
    [super viewDidUnload];
}

- (void)viewDidAppear:(BOOL)animated {
    self.parentViewController.title = @"Registreren";
}

- (IBAction)btnRegister:(id)sender {
    
    // Foutboodschap
    NSString *error_msg = @"";
    
    // Email validatie
    if(![self NSStringIsValidEmail:_txtEmail.text]) {
        error_msg = @"E-mailadres is niet geldig.";
    }
    
    // Tekstveld validatie
    if([_txtName.text isEqualToString:@""]|| [_txtSurname.text isEqualToString:@""] || [_txtPass.text isEqualToString:@""] || [_txtBirth.text isEqualToString:@""]) {
        error_msg = @"Vul alle velden volledig en correct in.";
    }
    
    if(![error_msg isEqualToString:@""]) {
        UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Fout"
                                                          message:error_msg
                                                         delegate:nil
                                                cancelButtonTitle:@"OK"
                                                otherButtonTitles:nil];
        [message show];
        return;
    }
    
    // Registratie URL
    NSString *myUrl = [NSString stringWithFormat:@"http://%@:8080/MyCinemaWebservice/webresources/REST/gebruiker", [[VariableStore sharedInstance] global_ip]];
    
    NSMutableDictionary *nameElements = [NSMutableDictionary dictionary];
    [nameElements setObject:_txtName.text forKey:@"Voornaam"];
    [nameElements setObject:_txtSurname.text forKey:@"Achternaam"];
    [nameElements setObject:_txtEmail.text forKey:@"Email"];
    [nameElements setObject:_txtBirth.text forKey:@"Geboortedatum"];
    [nameElements setObject:_txtPass.text forKey:@"Wachtwoord_hash"];
    
    // Variabele klaarzetten
    NSString *JSON = [nameElements JSONString];
    NSData *theData = [JSON dataUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString: myUrl];
    NSString *postLength = [NSString stringWithFormat:@"%d", [theData length]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    NSError *error = NULL;
    NSURLResponse *response = nil;
    
    // Request versturen
    [request setURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:theData];
    
    // Resultaat verwerken
    NSData *result = [NSURLConnection sendSynchronousRequest:request
                                           returningResponse:&response error:&error];
    NSString *resultString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
    
    // Geen boodschap is goed nieuws
    if ([resultString isEqualToString:@""]) {
        
        UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Registratie gelukt!"
                                                          message:@"U kan nu aanmelden."
                                                         delegate:nil
                                                cancelButtonTitle:@"OK"
                                                otherButtonTitles:nil];
        [message show];
       
    // Als er data terug komt wijst dit op een foutieve registratie
    } else {
        
        UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Registreren niet gelukt!"
                                                          message:@"Ga na of de gegevens juist zijn."
                                                         delegate:nil
                                                cancelButtonTitle:@"OK"
                                                otherButtonTitles:nil];
        [message show];
        
    }
    
}

-(BOOL) NSStringIsValidEmail:(NSString *)checkString
{
    // Testen of het email adres geldig is
    BOOL stricterFilter = YES;
    NSString *stricterFilterString = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSString *laxString = @".+@.+\\.[A-Za-z]{2}[A-Za-z]*";
    NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:checkString];
}

- (IBAction)txtNameReturn:(id)sender {
    [_txtName resignFirstResponder];
}

- (IBAction)txtSurnameReturn:(id)sender {
    [_txtSurname resignFirstResponder];
}

- (IBAction)txtEmailReturn:(id)sender {
    [_txtEmail resignFirstResponder];
}

- (IBAction)txtPassReturn:(id)sender {
    [_txtPass resignFirstResponder];
}

- (IBAction)txtBirthReturn:(id)sender {
    [_txtPass resignFirstResponder];
}

@end
